package jwt

import (
	gjwt "github.com/dgrijalva/jwt-go"
	"github.com/google/uuid"
)

type UserClaims struct {
	Account   string `json:"account"`
	Email     string `json:"email"`
	UserType  string `json:"user_type"`
	SessionId string `json:"session_id"`
	gjwt.StandardClaims
}

// Gen generates a token string.
func Gen(account, email, userType string) (string, error) {
	claims := UserClaims{
		account,
		email,
		userType,
		uuid.New().String(),
		gjwt.StandardClaims{
			//ExpiresAt: time.Now().Add(86400 * 30 * time.Second).Unix(),
			// the field can change to any.
			Issuer: "system",
		},
	}

	token := gjwt.NewWithClaims(gjwt.SigningMethodHS256, claims)

	// Sign and get the complete encoded token as a string using the secret
	// next time secret read from config
	return token.SignedString([]byte("secret"))
}

// Parse parses the token string and returns the claims.
func Parse(tokenString string) (*UserClaims, error) {
	tokenClaims, err := gjwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *gjwt.Token) (interface{}, error) {
		// next time secret read from config
		return []byte("secret"), nil
	})

	if err != nil {
		return nil, err
	}

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*UserClaims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
